// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.android.apps.moderator;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;

/**
 * A list entry representing a Google Moderator Topic
 */
public class TopicListEntry extends ModeratorListEntry {

  private final boolean headerMode;
  private int seriesId;
  private int topicId;

  public TopicListEntry(JSONObject jsonObject, boolean headerMode) {
    super(jsonObject);
    this.headerMode = headerMode;
    try {
      JSONObject idObject = jsonObject.getJSONObject("id");
      seriesId = idObject.getInt("seriesId");
      topicId = idObject.getInt("topicId");
    } catch (JSONException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public boolean clicked(Activity activity) {
    try {
      Intent intent = new Intent(activity, TopicActivity.class);
      intent.putExtra("seriesId", seriesId);
      intent.putExtra("topicId", topicId);
      intent.putExtra("name", jsonObject.getString("name"));
      activity.startActivity(intent);
    } catch (JSONException e) {
      throw new RuntimeException(e);
    }
    return true;
  }

  public void customizeView(View view, Activity activity) {
    try {
      ((TextView) view.findViewById(R.id.Name)).setText(jsonObject.getString("name"));
      final String description = jsonObject.getString("description");
      TextView descriptionTextView = (TextView) view.findViewById(R.id.Description);
      if ("".equals(description)) {
        if (headerMode) {
          descriptionTextView.setVisibility(View.GONE);
        } else {
          descriptionTextView.setText(R.string.default_topic_description);
        }
      } else {
        descriptionTextView.setText(description);
      }
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }

  public int getLayoutId() {
    return R.layout.topic_entry;
  }

  @Override
  protected String getUriString() {
    String e = Integer.toString(seriesId, 16);
    return "http://www.google.com/moderator/#15/e=" +
        e + "&t=" + e + "." + Integer.toString(topicId, 16);
  }
}
